package com.yunsc.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.utils.DateUtils;
import com.yunsc.common.utils.PageResult;
import com.yunsc.store.dao.YunscUserPointsLogDao;
import com.yunsc.store.dto.QueryPageDTO;
import com.yunsc.store.entity.YunscUserPointsLogEntity;
import com.yunsc.store.service.YunscUserPointsLogService;
import com.yunsc.store.service.YunscUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service("yunscUserPointsLogService")
public class YunscUserPointsLogServiceImpl extends ServiceImpl<YunscUserPointsLogDao, YunscUserPointsLogEntity> implements YunscUserPointsLogService {

    @Resource
    private YunscUserService userService;


    @Override
    public PageResult<YunscUserPointsLogEntity> queryUserPointsLog(Integer userId, Integer page) {
        LambdaQueryWrapper<YunscUserPointsLogEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscUserPointsLogEntity::getUserId, userId);
        lqw.orderByDesc(YunscUserPointsLogEntity::getCreateTime);
        Page<YunscUserPointsLogEntity> pageResult = this.page(new Page<>(page, 15), lqw);
        return PageResult.formatPageResult(pageResult.getRecords(), page, 15, pageResult.getTotal());
    }

    @Override
    public void addPointsLog(Integer userId, int pointsNum, String msg, Integer storeId) {
        YunscUserPointsLogEntity log = new YunscUserPointsLogEntity();
        log.setUserId(userId);
        log.setValue(pointsNum);
        log.setDescribe(msg);
        log.setStoreId(storeId);
        this.save(log);
    }

    @Override
    public PageResult<YunscUserPointsLogEntity> queryPointsLog(QueryPageDTO param, Integer storeId) {
        LambdaQueryWrapper<YunscUserPointsLogEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscUserPointsLogEntity::getStoreId, storeId);
        if (StringUtils.isNotEmpty(param.getBetweenTimeStart()) && StringUtils.isNotEmpty(param.getBetweenTimeEnd())){
            int startTime = DateUtils.convertIntToSeconds(param.getBetweenTimeStart());
            int endTime = DateUtils.convertIntToSeconds(param.getBetweenTimeEnd());
            lqw.between(YunscUserPointsLogEntity::getCreateTime, startTime, endTime);
        }
        Page<YunscUserPointsLogEntity> pageResult = this.page(new Page<>(param.getPage(), param.getPageSize()), lqw);
        pageResult.getRecords().forEach(item -> {
            item.setUser(userService.queryUserInfo(item.getUserId()));
        });
        return PageResult.formatPageResult(pageResult.getRecords(), param.getPage(), param.getPageSize(), pageResult.getTotal());
    }
}